var tz = tz || {},
    $$ = tz;


$$.closeWindow = function(action) {
    if (window.CloseOwnerWindow) {
        window.CloseOwnerWindow(action);
    } else {
        window.close();
    }
}

/**
 * miniui alert
 */
$$.alert = function(msg, callback) {
    mini.alert(msg, "提示", callback);
}

$$.confirm = function(msg, okCallBack, cancelCallBack) {
    mini.confirm(msg, "提示", function(action) {
        if (action == "ok" && typeof okCallBack == "function") {
            okCallBack();
        } else if (typeof cancelCallBack == "function") {
            cancelCallBack();
        }
    });
}

/**
 * miniui tips （默认5秒后）
 */
$$.tips = function(msg, timeout) {
    timeout = timeout || 3000;
    mini.showTips({
        content: msg,
        state: "info",
        x: "center",
        y: "top",
        timeout: timeout
    });
}

/**
 * 自动关闭消息提示（默认5秒后）
 */
$$.notify = function(msg, timeout, callback) {
    timeout = timeout || 3000;

    mini.showMessageBox({
        showHeader: true,
        showModal: false,
        title: "提示",
        iconCls: "mini-messagebox-info",
        message: msg,
        timeout: timeout,
        x: "center",
        y: "middle"
    });
}


$.ajaxSetup({
    type: "post",
    dataType: "json",
    complete: function() {
        mini.unmask(document.body);
    }
})

$$.mask = function(el) {
    mini.mask({
        el: el,
        cls: 'mini-mask-loading',
        html: '加载中...'
    });
}

$$.unmask = function(el) {
    mini.unmask(el);
}

/**
 * 添加遮罩的ajax
 */
$$.ajax = function(url, data, callback, setting) {
    mini.mask({
        el: document.body,
        cls: 'mini-mask-loading',
        html: '加载中...'
    });

    if (typeof arguments[1] === "function") {
        setting = arguments[2];
        callback = arguments[1];
        data = {};
    }

    var request = setting || {};

    $.extend(request, {
        url: $$.url(url),
        data: data,
        success: function(r) {
            if (r.msg && !request.ignore) {
                tz.notify(r.msg);
            }

            if (typeof callback === "function") {
                r.success = (r.code === "00");
                callback(r);
            }
        }
    });

    $.ajax(request);
}

/**
 * 包装miniui get函数
 */
$$.get = function(e) {
    return mini.get(e);
}

/**
 * 添加miniui form 加载数据函数
 */
$$.form = function(e) {
    var form = new mini.Form(e);

    form.getErrMsg = function() {
        var form_ = this;
        form_.validate();
        if (form.isValid()) {
            return;
        }

        var errFields = form_.getErrors();
        var errMsg = [];

        for (var i = 0, l = errFields.length; i < l; i++) {
            var errField = errFields[i];

            var label = errField.label;
            if (label) {
                errMsg.push('【' + label + '】' + errField.errorText);
            } else {
                errMsg.push(errField.errorText);
            }
        }
        return errMsg.join("，");
    };

    form.load = function(url, param, callback) {
        mini.mask({
            el: document.body,
            cls: 'mini-mask-loading',
            html: '加载中...'
        });
        var form_ = this;
        $.post($$.url(url), param, function(r) {
            mini.unmask(document.body);
            if (!r.code === "00") {
                return tz.notify(r.msg);
            }
            form_.setData(r.data);

            if (typeof callback === "function") {
                callback(r.data, form_);
            }
        });
        return form;
    };


    form.submit = function(url, submitData, callback, opt) {
        mini.mask({
            el: document.body,
            cls: 'mini-mask-loading',
            html: '提交中...'
        });

        if (typeof arguments[1] === "function") {
            callback = arguments[1];
            submitData = null;
        }

        var form_ = this;

        form_.validate();
        if (!form_.isValid()) {
            mini.unmask(document.body);
            return tz.alert(form_.getErrMsg());
        }

        var data = null;

        if (!submitData) {
            data = form_.getData(false);
        } else {
            data = submitData;
        }

        tz.log(data);

        var request = opt || {};

        $.extend(request, {
            url: $$.url(url),
            data: data,
            success: function(r) {
                if (r.code === "00") {
                    form_.setData($.extend(submitData, r.data));
                }

                if (r.msg) {
                    tz.alert(r.msg, function() {
                        if (typeof callback === "function") {
                            r.success = (r.code === "00");
                            callback(r, form_);
                        }
                    });
                } else {
                    if (typeof callback === "function") {
                        r.success = (r.code === "00");
                        callback(r, form_);
                    }
                }
            }
        });

        $.ajax(request);

        return form;
    };

    return form;
}

/**
 * @param title 标题
 * @param url   地址
 * @param ondestroy 销毁事件
 * @param opts {width:宽, height:高, minimize:是否显示最小化, winId:窗口ID最小化窗口标识,空默认生成uuid}
 */
$$.open = function(title, url, ondestroy, opts) {
    if (!(typeof arguments[2] === "function")) {
        opts = arguments[2];
        ondestroy = null;
    }

    if (opts) {
        if (typeof opts.width === 'string') {
            opts.width = parseInt($$.getWinWidth() * parseInt(opts.width.replace(/\%/g, '')) / 100);
        }

        if (typeof opts.height === 'string') {
            opts.height = parseInt($$.getWinHeight() * parseInt(opts.height.replace(/\%/g, '')) / 100);
        }
    }

    if (opts && opts.minimize && opts.winId) {
        var win = $$.winBar.open(opts.winId);
        if (win) return win;
    }

    var win = mini.open($.extend({
        url: $$.url(url),
        title: title,
        ondestroy: function(action) {
            var iFrame = this.getIFrameEl();
            var parentWin = iFrame.contentWindow;
            parentWin.action = action;
            parentWin.isOk = function() {
                return action === "ok";
            }
            if (typeof ondestroy === 'function') {
                ondestroy(parentWin, action);
            }
        }
    }, opts));

    if (opts && opts.minimize) {
        var winId = opts.winId || $$.uuid();
        tz.winBar.add(winId, win);
    }
    return win;
}

$$.getTopWindow = function() {
    var win = window;
    for (var i = 0; i < 100; i++) {
        try {
            tz.log(i);
            win.parent.name;
            if (win == win.parent) {
                break;
            }
            win = win.parent;
        } catch (e) {
            return win
        }
    }
    return win;
}

$$.getWinWidth = function() {
    return $($$.getTopWindow()).width();

}

$$.getWinHeight = function() {
    return $($$.getTopWindow()).height();
}

// 窗口最小化
$$.winBar = {
    add: function(id, win) {
        var w = $$.getTopWindow();
        if (!w.windowArray) {
            w.windowArray = {};
        }

        win.on('destroy', function() {
            tz.winBar.remove(id);
        });
        win.setButtons([{ html: '<span class="fa fa-minus" style="position:relative;top:2px;" onclick="tz.winBar.make(\'' + id + '\')"></span>' }, 'close']);

        var jslength = 0;
        for (var key in w.windowArray) {
            jslength++;
        }
        if (jslength > 6) {
            return;
        }
        w.windowArray[id] = win;
        return win;
    },

    make: function(id) {
        var w = $$.getTopWindow();
        if (!w.windowArray) {
            return;
        }

        var jslength = 0;
        for (var key in w.windowArray) {
            jslength++;
        }

        if (jslength > 6) {
            return w.tz.tips('亲！打开太多窗口了');
        }

        var win = w.windowArray[id];
        if (!win) {
            return;
        }
        win.hide();

        if (w.$('.winbar').length < 1) {
            w.$('body').append('<span class="winbar"></span>');
        }

        if (!w.$('body #' + id).html()) {
            w.$('.winbar').append('<span id="' + id + '" class="winItem" onclick="tz.winBar.open(\'' + id + '\')" title="' + win.getTitle() + '"><span>' + win.getTitle() + '</span><span onclick="tz.winBar.close(\'' + id + '\')" class="closeWindow" ">X</span></span>');
        }
    },

    remove: function(id) {
        var w = $$.getTopWindow();
        if (!w.windowArray) {
            return;
        }
        delete w.windowArray[id];
        w.$('#' + id).remove();
    },

    close: function(id) {
        var w = $$.getTopWindow();
        if (!w.windowArray) {
            return;
        }
        var win = w.windowArray[id];
        try {
            win.destroy();
        } catch (e) {
            $$.winBar.remove(id);
        }
    },

    open: function(id) {
        var w = $$.getTopWindow();
        if (!w.windowArray) {
            return;
        }
        var win = w.windowArray[id];
        if (!win) {
            return;
        }
        win.show();
        return win;
    }
}

$$.curtain = function(id, outSide, expand) {
    var curtain = $('#' + id);

    // 展开
    curtain.expand = function() {
        setTimeout(function() {
            curtain.show('fast');
            $('#' + outSide).addClass('tz-curtain-body-mask');
        }, 50);

        if (mini) {
            setTimeout(function() {
                mini.layout();
            }, 500);
        }

        if (expand && typeof expand === 'function') {
            expand();
        }
    };

    curtain.find('.close-btn').on('click', function() {
        curtain.collapse();
    });

    // 收起
    curtain.collapse = function() {
        curtain.hide();
        $('#' + outSide).removeClass('tz-curtain-body-mask');
    }

    if (outSide) {
        $('#' + outSide).on('click', function() {
            curtain.collapse();
        })
    }

    return curtain;
}